package com.zkmonitor.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zkmonitor.dao.NodeDAO;
import com.zkmonitor.dao.SnapZkTree;

/**
 * 查询整个zk快照，将节点路径保存到mysql
 * 
 * @author HouYijun 2018-5-31
 * 
 */
@Service
public class SnapService {

	@Autowired
	SnapZkTree snapZkTree;

	@Autowired
	private NodeDAO nodeDAO;
	
	public List<String> query_clustor(String clustor) {
		try{
			return snapZkTree.query_clustor(clustor);
		}
		catch(Exception e){
			e.printStackTrace();
			return Collections.EMPTY_LIST;
		}
	}

	public void do_cluster(String cluster) throws Exception {
		BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
		queue.add("/");

		snapZkTree.connect();
		snapZkTree.clear_clustor(cluster);

		while (!queue.isEmpty()) {
			String root = queue.take();
			
			List<String> subNames = nodeDAO.getChildren(cluster, root);
			List<String> childPath =new ArrayList<String>();
			
			if (subNames != null && !subNames.isEmpty()) {
				for (String childName:subNames){
					if (root.equals("/")){
						childPath.add(root+childName);
					}else{
						childPath.add(root+"/"+childName);
					}
				}
				snapZkTree.insert_db(cluster, childPath);
				queue.addAll(childPath);
			}
		}

		snapZkTree.close();

	}

}
